package org.example.controller;
import org.example.DAO.ContentDAO;
import org.example.entity.Content;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@WebServlet(
        name = "ContentController",
        urlPatterns = {"/content/*"},
        loadOnStartup = 1 // 确保Servlet在应用启动时初始化
)
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2,
        maxFileSize = 1024 * 1024 * 10,
        maxRequestSize = 1024 * 1024 * 50)
public class ContentController extends HttpServlet {
    private static final int PAGE_SIZE = 10;
    private ContentDAO contentDAO;

    @Override
    public void init() throws ServletException {
        super.init();
        // 确保DAO在Servlet初始化时创建
        contentDAO = new ContentDAO();
        System.out.println("ContentController初始化完成，DAO已创建");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getPathInfo();
        try {
            if (action == null) action = "/list";

            System.out.println("处理GET请求: " + action);

            switch (action) {
                case "/add":
                    showAddForm(request, response);
                    break;
                case "/edit":
                    showEditForm(request, response);
                    break;
                case "/delete":
                    deleteContent(request, response);
                    break;
                case "/status":
                    updateContentStatus(request, response);
                    break;
                case "/list":
                default:
                    listContents(request, response);
                    break;
            }
        } catch (SQLException ex) {
            handleError(request, response, "数据库操作错误: " + ex.getMessage(), ex);
        } catch (Exception ex) {
            handleError(request, response, "系统错误: " + ex.getMessage(), ex);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getPathInfo();
        try {
            if (action == null) action = "/list";

            System.out.println("处理POST请求: " + action);

            switch (action) {
                case "/movies":
                    showMoviesPage(request, response);
                    break;
                case "/books":
                    showBooksPage(request, response);
                    break;
                case "/add":
                    addContent(request, response);
                    break;
                case "/update":
                    updateContent(request, response);
                    break;
                default:
                    listContents(request, response);
                    break;
            }
        } catch (SQLException | IOException ex) {
            handleError(request, response, "内容处理错误: " + ex.getMessage(), ex);
        } catch (Exception ex) {
            handleError(request, response, "系统错误: " + ex.getMessage(), ex);
        }
    }

    private void handleError(HttpServletRequest request, HttpServletResponse response,
                             String message, Exception ex)
            throws ServletException, IOException {
        System.err.println(message);
        ex.printStackTrace();
        request.setAttribute("errorMessage", message);
        request.getRequestDispatcher("/error.jsp").forward(request, response);
    }

    private void listContents(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        System.out.println("开始加载内容列表...");

        int page = 1;
        String pageParam = request.getParameter("page");
        if (pageParam != null && !pageParam.isEmpty()) {
            try {
                page = Integer.parseInt(pageParam);
                if (page < 1) page = 1;
            } catch (NumberFormatException e) {
                System.out.println("无效的页码参数: " + pageParam + ", 使用默认页码1");
            }
        }

        String type = request.getParameter("type");
        System.out.println("查询参数 - 页码: " + page + ", 类型: " + (type != null ? type : "全部"));

        try {
            // 确保DAO已初始化
            if (contentDAO == null) {
                contentDAO = new ContentDAO();
                System.out.println("在listContents中创建了新的DAO实例");
            }

            List<Content> contents = contentDAO.getAllContents(page, PAGE_SIZE, type);
            int totalCount = contentDAO.getContentCount(type);
            int totalPages = (int) Math.ceil((double) totalCount / PAGE_SIZE);

            System.out.println("查询结果: " + contents.size() + "条内容");
            System.out.println("总记录数: " + totalCount + ", 总页数: " + totalPages);

            request.setAttribute("contents", contents);
            request.setAttribute("currentPage", page);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("type", type);

            // 传递操作结果
            String actionResult = request.getParameter("actionResult");
            if (actionResult != null) {
                request.setAttribute("actionResult", actionResult);
            }
        } catch (SQLException e) {
            System.err.println("列表查询失败: " + e.getMessage());
            request.setAttribute("errorMessage", "无法加载内容列表: " + e.getMessage());
        }

        request.getRequestDispatcher("/content-management.jsp").forward(request, response);
    }
    private void showAddForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 禁止缓存
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");

        // 初始化空内容对象
        Content newContent = new Content();
        newContent.setStatus("draft"); // 设置默认状态
        request.setAttribute("content", newContent);

        request.getRequestDispatcher("/add-content.jsp").forward(request, response);
    }
    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        String id = request.getParameter("id");
        Content existingContent = contentDAO.getContentById(id);
        if (existingContent == null) {
            response.sendRedirect(request.getContextPath() + "/content/list?error=contentNotFound");
            return;
        }
        request.setAttribute("content", existingContent);
        request.getRequestDispatcher("/edit.jsp").forward(request, response);
    }
    private void showMoviesPage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        List<Content> movies = contentDAO.getContentsByType("movie");
        request.setAttribute("movies", movies);
        request.getRequestDispatcher("/movies.jsp").forward(request, response);
    }

    private void showBooksPage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        List<Content> books = contentDAO.getContentsByType("book");
        request.setAttribute("books", books);
        request.getRequestDispatcher("/books.jsp").forward(request, response);
    }
    private void addContent(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException, ServletException, ParseException {
        Content content = new Content();
        setContentPropertiesFromRequest(request, content);
        // 处理封面图片上传
        Part filePart = request.getPart("cover");
        if (filePart != null && filePart.getSize() > 0) {
            String fileName = saveUploadedFile(filePart);
            content.setCoverUrl("/uploads/" + fileName);
        }
        String id = contentDAO.addContent(content);
        request.setAttribute("actionResult", "addSuccess");
        listContents(request, response);
    }
    private void updateContent(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException, ParseException {
        String id = request.getParameter("id");
        Content content = contentDAO.getContentById(id);
        if (content == null) {
            response.sendRedirect(request.getContextPath() + "/content/list");
            return;
        }
        setContentPropertiesFromRequest(request, content);
        // 处理封面图片更新
        Part filePart = null;
        try {
            filePart = request.getPart("cover");
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
        if (filePart != null && filePart.getSize() > 0) {
            // 删除旧封面
            deleteCoverFile(content.getCoverUrl());
            // 保存新封面
            String fileName = saveUploadedFile(filePart);
            content.setCoverUrl("/uploads/" + fileName);
        } else {
            // 未上传新封面，保留原有封面
            String existingCover = request.getParameter("existingCover");
            if (existingCover != null && !existingCover.isEmpty()) {
                content.setCoverUrl(existingCover);
            }
        }
        contentDAO.updateContent(content);
        response.sendRedirect(request.getContextPath() + "/content/edit?id=" + id + "&actionResult=updateSuccess");
    }
    // 在ContentController中
    private void deleteContent(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        String id = request.getParameter("id");

        // 删除前获取内容类型用于广播
        Content content = contentDAO.getContentById(id);
        String type = content != null ? content.getType() : "unknown";

        contentDAO.deleteContent(id);

        // 设置删除消息
        request.getSession().setAttribute("deletedContent", id);
        request.getSession().setAttribute("deletedType", type);

        response.sendRedirect(request.getContextPath() + "/content/list?actionResult=deleteSuccess");
    }
    private void updateContentStatus(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        String id = request.getParameter("id");
        String status = request.getParameter("status");
        if (id != null && status != null) {
            contentDAO.updateContentStatus(id, status);
        }
        response.sendRedirect(request.getContextPath() + "/content/list?actionResult=statusUpdateSuccess");
    }
    private void deleteCoverFile(String thumbnailUrl) {
        if (thumbnailUrl != null && !thumbnailUrl.isEmpty() && !thumbnailUrl.startsWith("https://")) {
            try {
                String realPath = getServletContext().getRealPath(thumbnailUrl);
                if (realPath != null) {
                    File file = new File(realPath);
                    if (file.exists()) {
                        file.delete();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private String saveUploadedFile(Part filePart) throws IOException {
        String fileName = System.currentTimeMillis() + "_" + getSubmittedFileName(filePart);
        String uploadPath = getServletContext().getRealPath("/uploads");
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) uploadDir.mkdirs();
        File file = new File(uploadDir, fileName);
        filePart.write(file.getAbsolutePath());
        return fileName;
    }
    private String getSubmittedFileName(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                return cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
    private void setContentPropertiesFromRequest(HttpServletRequest request, Content content)
            throws ParseException {
        content.setTitle(request.getParameter("title"));
        content.setType(request.getParameter("type"));
        content.setDescription(request.getParameter("description"));
        content.setStatus(request.getParameter("status"));
        // 类型特定字段
        String contentType = request.getParameter("type");
        if ("movie".equals(contentType)) {
            content.setDirector(request.getParameter("director"));
            content.setActors(request.getParameter("actors"));
        } else if ("book".equals(contentType)) {
            content.setAuthor(request.getParameter("author"));
            content.setPublisher(request.getParameter("publisher"));
        } else if ("music".equals(contentType)) {
            content.setArtist(request.getParameter("artist"));
            content.setAlbum(request.getParameter("album"));
        }
    }
}